<?php

namespace backend\services\mall;

use Yii;
use yii\helpers\Json;
use backend\extensions\ApiBaseService;
use backend\models\mall\page\MallPage;
use backend\models\mall\page\MallPageCom;
use backend\models\mall\page\MallPageComGoods;
use api\services\goods\GoodsService;
/**
 * 专题
 */
class MallPageService extends ApiBaseService
{

    /**
     * 列表
     * @param array $params 参数
     * @return array
     * **/
    public static function getList($params)
    {
        //检索条件
        $condition = ['AND'];
        if ($params['name']) {
            $condition[] = ['like', 'name', $params['name'] ?? ''];
        }
        $list = MallPage::getDataAll($condition, $params['page'], $params['page_size']);
        return $list;
    }

    /**
     * 详情
     * @param array $params 参数 
     * **/
    public static function detail($params)
    {
        $condition = ['id' => $params['id']];
        $info = MallPage::getDataOne($condition);
        $com = MallPageCom::getAll(['page_id' => $params['id']]) ?? [];
        $list = [];
        if (!empty($com)) {
            foreach ($com as $key => $item) {
                $list[] =  json_decode($item['value'], true);
            }
        }

        $info['info'] = $list;
        return $info;
    }

    /**
     * 新增
     * @param array $params 参数 
     * **/
    public static function create($params)
    {
        // $is_home = $params['is_home'] ?? MallPage::IS_HOME_NO;
        // if ($is_home == MallPage::IS_HOME_YES) {
        //     $home_special = MallPage::find()->where(['is_home' => MallPage::IS_HOME_YES])->one();
        //     if ($home_special) {
        //         return self::jsonError('首页专题只能设置一个');
        //     }
        // }

        $time = date('Y-m-d H:i:s');
        $params['create_time'] = $time;

        $page_com_data = empty($params['info']) ? [] : json_decode($params['info'], true);
        unset($params['info']);
        // 保存数据——专题数据——楼层数据——商品数据
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 保存专题
            $page_id =  MallPage::create($params);
            foreach ($page_com_data as $key => $item) {

                $sp_data = [
                    'page_id' => $page_id,
                    'value' => json_encode($item),
                    'type' => $item['type'],
                ];
                // var_dump($sp_data);
                // 保存楼层
                $sf_id = MallPageCom::create($sp_data);

                if (isset($item['goods_ids']) && !empty($item['goods_ids'])) {
                    $rows = [];
                    $barcodesArr = array_unique(explode(',', $item['goods_ids']));
                    foreach ($barcodesArr as $bItem) {
                        $rows[] = [
                            'page_com_id' => $sf_id,
                            'gid' => $bItem,
                            'page_id' => $page_id,
                        ];
                    }
                    // 保存商品
                    \Yii::$app->db->createCommand()->batchInsert(MallPageComGoods::tableName(), array_keys($rows[0]), $rows)->execute();
                }
            }

            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }

    /**
     * 更新
     * @param array $params 参数 
     * **/
    public static function update($params)
    {
        $id = $params['id'];
        // $is_home = $params['is_home'] ?? MallPage::IS_HOME_NO;
        // if ($is_home == MallPage::IS_HOME_YES) {
        //     $home_special = MallPage::find()
        //         ->where(['is_home' => MallPage::IS_HOME_YES])
        //         ->andWhere(['!=', 'id', $id])->one();
        //     if ($home_special) {
        //         return self::jsonError('首页专题只能设置一个');
        //     }
        // }
        // 轮播图
        $page_data = [
            'name' => $params['name']
        ];

        $page_com_data = empty($params['info']) ? [] : json_decode($params['info'], true);
        unset($params['info']);
        // 保存数据——专题数据——楼层数据——商品数据
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 保存专题
            MallPage::updateData($page_data, ['id' => $id]);
            MallPageCom::deleteAll(['page_id' => $id]);
            MallPageComGoods::deleteAll(['page_id' => $id]);

            foreach ($page_com_data as $key => $item) {
                $sp_data = [
                    'page_id' => $id,
                    'value' => json_encode($item),
                    'type' => $item['type'],
                ];
                // 保存楼层
                $sf_id = MallPageCom::create($sp_data);

                if (isset($item['goods_ids']) && !empty($item['goods_ids'])) {
                    $rows = [];
                    $barcodesArr = array_unique(explode(',', $item['goods_ids']));
                    foreach ($barcodesArr as $bItem) {
                        $rows[] = [
                            'page_com_id' => $sf_id,
                            'gid' => $bItem,
                            'page_id' => $id,
                        ];
                    }
                    // 保存商品
                    \Yii::$app->db->createCommand()->batchInsert(MallPageComGoods::tableName(), array_keys($rows[0]), $rows)->execute();
                }
            }

            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }

    /**
     * 删除
     * @param array $params 参数 
     * **/
    public static function delete($params)
    {
        $id = $params['id'];
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 保存专题
            MallPage::del(['id' => $id]);
            MallPageCom::deleteAll(['page_id' => $id]);
            MallPageComGoods::deleteAll(['page_id' => $id]);

            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }


    // 获取商品列表
    public static function pageGoodsList($params)
    {
        $ids = explode(',', $params['ids']);
        if (empty($ids)) {
            return self::jsonSuccess([]);
        }
        $goods = GoodsService::getGoodsInfo($ids, 1, 1);
        return self::jsonSuccess($goods);
    }
}
